//
//  AIGirlMsgChangeInterestView.swift
//  AIGirl
//
//  Created by Rae on 2024/1/30.
//

import UIKit
import SwiftEntryKit

class AIGirlMsgChangeInterestView: UIView, AnimationProtocol, AnimationDelegate, UorInXNetworkProtocol {

    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: .screenHeight)
    }
    
    func animationContainerViewStyle() -> AnimationViewStyle {
        .bottom
    }
    
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white).font(30.font_bold).alignment(.center)
        .text("Choose 5 tags you like").end()
    private lazy var doneButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(21.font_bold).corner(20)
        .text("Done").end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var dataList:[AIGirlInterestModel] = [] {
        didSet{
            collectionView.reloadData()
        }
    }
    var saveClosure: (() -> Void)?
    var dismissClosure: (() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .black.alpha(0.4)
        
        subviews{
            titleLabel
            collectionView
            doneButton
        }
        
        titleLabel.top(.navi_height + 45).centerHorizontally()
        doneButton.height(50).width(300).bottom(105).centerHorizontally()
        collectionView.leading(0).trailing(0)
        collectionView.Top == titleLabel.Bottom + 50
        collectionView.Bottom == doneButton.Top - 30
        
        let layout = UICollectionViewLeftAlignedLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.sectionInset = UIEdgeInsets(top: 0, left: 20.0, bottom: 0, right: 20.0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(AIGirlInterestItem.self, forCellWithReuseIdentifier: AIGirlInterestItem.description())
            v.showsVerticalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        doneButton.addTarget(self, action: #selector(clickDoneButton), for: .touchUpInside)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismissClosure?()
    }
    
    @objc private func clickDoneButton(){
        
        var nameArr = [String]()
        var idArr = [String]()
        for model in dataList {
            if model.isSel {
                nameArr.append(model.name)
                idArr.append(String(model.id))
            }
        }
        if nameArr.count == 0 {
            "Please choose at least one topic that interests you!".toast_error
            return
        }
        let nameString = nameArr.joined(separator: ",")
        let idString = idArr.joined(separator: ",")
        request.start(.saveUserInterests(ids: idString)) { result in
            if result.isSuccessful {
                "Successful!".toast_success
                self.saveClosure?()
            }
        }
    }
}

extension AIGirlMsgChangeInterestView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlInterestItem.description(), for: indexPath) as? AIGirlInterestItem else { return UICollectionViewCell() }
        item.model = dataList[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
//        var model = dataList[indexPath.row]
//        model.isSel = !model.isSel
//        dataList[indexPath.row] = model
//        collectionView.reloadData()
        var index = 0
        var model = dataList[indexPath.row]
        model.isSel = !model.isSel
        for md in dataList {
            if md.isSel {
                index += 1
            }
        }
        if index >= 5 && model.isSel {
            return
        }
        dataList[indexPath.row] = model
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let model = dataList[indexPath.row]
        var w = model.name.caculateWidth(CGSize(width: 110, height: 40), 16.font_medium!)
        w = w + 30.0
        return CGSize(width: w, height: 40)
    }
}
